package com.ww.app.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.ww.model.user.pojos.ApUser;
import com.ww.utils.common.JwtUtils;
import com.ww.utils.common.Payload;
import com.ww.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;

/**
 * 统一鉴权过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Value("${leadnews.jwt.publicKeyPath}")
    private String publicKeyPath;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断请求是否为登录请求
        String uri = request.getPath().toString();
        if (uri.contains("login")) {
            //放行
            return chain.filter(exchange);
        }
        //判断请求头是否包含token
        String token = request.getHeaders().getFirst("token");
        if (StrUtil.isEmpty(token)) {
            //返回401，代表权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求（但不放行）
            return response.setComplete();
        }
        //校验token是否合法（用公钥解析token是否合法）
        try {
            //获取公钥信息
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            //获取载荷
            Payload<ApUser> payload = JwtUtils.getInfoFromToken(token, publicKey, ApUser.class);
            Integer id = payload.getInfo().getId();
            //id放入请求头
            request.mutate().header("userId", id.toString());
            return chain.filter(exchange);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束请求（但不放行）
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
